package handler

import (
	"common"
	"common/biz"
	"common/logs"
	"core/repo"
	"core/service"
	"encoding/json"
	"fmt"
	"framework/remote"
	"game/logic"
	"game/models/request"
	hall "hall/handler"
	"strconv"
)

type GameHandler struct {
	um               *logic.CardManager
	userService      *service.UserService
	warehouseService *service.WarehouseService
	base             *hall.BaseHandler
}

func (h *GameHandler) CardRoomMessageNotify(session *remote.Session, msg []byte) any {
	logs.Info("[Game] RoomMessageNotify msg:%v", string(msg))
	uid, _ := strconv.Atoi(session.GetUid())
	if uid <= 0 {
		logs.Error("[Game] RoomMessageNotify err:未获取到UID")
		return common.F(biz.InvalidUsers)
	}
	if err := h.base.Login(nil, uint(uid), session.GetSid()); err != nil {
		return common.F(err)
	}
	var req request.RoomMessageReq
	if err := json.Unmarshal(msg, &req); err != nil {
		logs.Error("[Game]用户%d RoomMessageNotify err:缺少参数 req=%v,err=%v", uid, req, err)
		return common.F(biz.RequestDataError)
	}
	//room去处理这块的业务
	roomId, ok := session.Get("roomId")
	if !ok || roomId == "" {
		logs.Error("[Game]用户%d RoomMessageNotify err:房间不存在 req=%v", uid, roomId)
		return common.F(biz.NotInRoom)
	}
	rm := h.um.GetRoomById(fmt.Sprintf("%v", roomId))
	if rm == nil {
		logs.Error("[Game]用户%d RoomMessageNotify err:房间不存在 req=%v", uid, roomId)
		return common.F(biz.NotInRoom)
	}
	rm.RoomMessageHandle(session, uint(uid), req, h.warehouseService)
	return nil
}

func (h *GameHandler) CardGameMessageNotify(session *remote.Session, msg []byte) any {
	logs.Info("[Game] GameMessageNotify msg:%v", string(msg))
	uid, _ := strconv.Atoi(session.GetUid())
	if uid <= 0 {
		logs.Error("[Game] GameMessageNotify err:未获取到UID")
		return common.F(biz.InvalidUsers)
	}
	if err := h.base.Login(nil, uint(uid), session.GetSid()); err != nil {
		return common.F(err)
	}
	roomId, _ := session.Get("roomId")
	//if !ok {
	//	return common.F(biz.NotInRoom)
	//}
	rm := h.um.GetRoomById(fmt.Sprintf("%v", roomId))
	if rm == nil {
		logs.Error("[Game]用户%d GameMessageNotify err:房间不存在 req=%v", uid, roomId)
		return common.F(biz.NotInRoom)
	}
	rm.GameMessageHandle(session, uint(uid), msg)
	return nil
}

func NewGameHandler(r *repo.Manager, um *logic.CardManager) *GameHandler {
	return &GameHandler{
		um:               um,
		userService:      service.NewUserService(r),
		warehouseService: service.NewWarehouseService(r),
		base:             hall.NewBaseHandler(r),
	}
}
